﻿using System;
using System.ComponentModel;
using EventAggregator;

namespace EAWpfSample
{
    public sealed class ProgressViewModel : INotifyPropertyChanged
    {
        private double _maximum;
        private double _minimum;
        private double _value;

        public ProgressViewModel()
        {
            Minimum = 0;
            Maximum = 100;
            Value = 0;

            this.Subscribe(EventId.Default.DoWork, HandleDoWork);
            this.Subscribe(EventId.Default.WorkProgress, HandleWorkProgress);
        }

        public double Minimum
        {
            get { return _minimum; }

            set
            {
                if (Math.Abs(_minimum - value) < double.Epsilon)
                {
                    return;
                }

                _minimum = value;

                RaisePropertyChanged("Minimum");
            }
        }

        public double Maximum
        {
            get { return _maximum; }

            set
            {
                if (Math.Abs(_maximum - value) < double.Epsilon)
                {
                    return;
                }

                _maximum = value;

                RaisePropertyChanged("Maximum");
            }
        }

        public double Value
        {
            get { return _value; }

            set
            {
                if (Math.Abs(_value - value) < double.Epsilon)
                {
                    return;
                }

                _value = value;

                RaisePropertyChanged("Value");
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        private void HandleDoWork(EventMessage eventMessage)
        {
            Value = 0;
            Maximum = eventMessage.GetValue<TimeSpan>("TimeSpan").TotalSeconds;
        }

        private void HandleWorkProgress(EventMessage eventMessage)
        {
            Value = eventMessage.GetValue<int>("Progress");
        }

        private void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}